package com.media.appmedia.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;

/**
 * 
 * 作者: Rose 业务名: 功能说明: 存储sd工具类 编写日期: 2014-3-6
 * 
 */
public class FileUtils {
	private static final String TAG = "FileUtils";

	/**
	 * 判断sdcard的状态
	 */
	public static boolean isStateUseful() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据图片字节数组存储到sdcard
	 */
	public static boolean writeImageToSdcard(byte b[], String imagePath) {
		boolean flag = false;
		FileOutputStream fos = null;
		try {
			// 获取当前图片的名称
			String fileName = imagePath
					.substring(imagePath.lastIndexOf("/") + 1);
			File file = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
					fileName);
			fos = new FileOutputStream(file);
			fos.write(b);
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	/**
	 * 
	 * 方法说明： 生产存储时的路劲
	 * 
	 * @return
	 */
	public static String createImgLoad() {
		return Environment.getExternalStorageDirectory() + File.separator
				+ "sgfcLoadCache";
	}

	/*
	 * 通过递归得到某一路径下所有的目录及其文件
	 */
	private static List<String> getFiles(String filePath) {
		ArrayList<String> filelist = new ArrayList<String>();
		File root = new File(filePath);
		root.mkdirs();
		File[] files = root.listFiles();
		for (File file : files) {
			filelist.add(file.getAbsolutePath());
		}
		return filelist;
	}
	/**
	 * 
	 * 方法说明：判断当前路径标示的图片是否已经存在本地
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isExist(String fileName){
		ArrayList<String > files = (ArrayList<String>) getFiles(createImgLoad());
		String url = createImgLoad() + File.separator + fileName.hashCode()+".png";
		for(int i=0;i<files.size();i++){
			if(url.equals(files.get(i))){
				return true;
			}
		}
		return false;
	}
	
	public static void deleteImage(String fileName){
			String files = createImgLoad();
			File file = new File(files, fileName.hashCode() + ".png");
			System.out.println("");
			if(file.exists()){
				file.delete();
			}
	}

}
